package com.lboyang.seckill.rabbitmq;

import com.lboyang.seckill.entity.SeckillMessage;
import com.lboyang.seckill.entity.SeckillOrder;
import com.lboyang.seckill.entity.User;
import com.lboyang.seckill.entity.vo.GoodsVo;
import com.lboyang.seckill.entity.vo.RespBean;
import com.lboyang.seckill.entity.vo.RespBeanEnum;
import com.lboyang.seckill.service.GoodsService;
import com.lboyang.seckill.service.OrderService;
import com.lboyang.seckill.util.JsonUtil;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @Description:
 * @Author: Aiguodala
 * @CreateDate: 2021/5/30 11:19
 */
@Service
@Slf4j
public class MQCustomer {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderService orderService;

    @RabbitListener(queues = "seckillQueue")
    public void receive(String message) {
        log.info("接收的消息：" + message);
        SeckillMessage seckillMessage = JsonUtil.jsonStr2Object(message, SeckillMessage.class);
        Long goodId = seckillMessage.getGoodsId();
        User user = seckillMessage.getUser();
        //判断库存
        GoodsVo goodsVo = goodsService.getGoodsVoById(goodId);
        if (goodsVo.getStockCount() < 1) {
            return;
        }
        //判断是否重复抢购
        SeckillOrder seckillOrder =
                (SeckillOrder) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodId);
        if (seckillOrder != null) {
            return;
        }
        //下单操作
        orderService.seckill(user, goodsVo);
    }
}
